import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { Edge, Graph, Node } from '@antv/x6';
import { GraphService } from '../util/graph.service';


@Component({
  selector: 'app-cell-set',
  templateUrl: './cell-set.component.html',
  styleUrls: ['./cell-set.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CellSetComponent implements OnInit {
  graph!: Graph;
  stepName!: string;

  currentNode: Node<Node.Properties> | undefined;
  currentEdge: Edge<Edge.Properties> | undefined;

  constructor(
    private cd: ChangeDetectorRef,
    private graphService: GraphService
  ) {
    this.graphService.graph$.subscribe((graph) => {
      if (graph) {
        this.graph = graph;
      }
    });

    this.graphService.btnJson$.subscribe((flag) => {
      if (flag) {
        this.export();
      } else {
        this.import();
      }
      this.cd.markForCheck();
    });
  }

  ngOnInit(): void {

    this.graph.on('node:selected', ({ node }) => {
      this.currentNode = undefined;
      // console.log('node::selected::', node);
      this.stepName = node.attrs?.text.text as string;
      this.currentNode = node;
      this.cd.markForCheck();
    });

    this.graph.on('node:unselected', ({ node }) => {
      // console.log('node::unselected::', node);
      this.currentNode = undefined;
      this.cd.markForCheck();
    });


    this.graph.on('edge:selected', ({ edge }) => {
      // console.log('edge::selected::', edge);
      this.currentEdge = edge;

      this.cd.markForCheck();
    });

    this.graph.on('edge:unselected', ({ edge }) => {
      // console.log('edge::unselected::', edge);

      this.currentEdge = undefined;
      this.cd.markForCheck();
    });

    this.graph.on('cell:change:attrs', ({ cell, current }) => {
      // console.log('cell:change:attrs', current);
      this.stepName = current?.text.text as string;
      this.cd.markForCheck();
    });

  }

  jsonData!: any;

  export() {
    this.jsonData = this.graph.toJSON();
    console.log(this.jsonData);
    this.cd.markForCheck();
  };

  import() {
    this.graph.fromJSON(this.jsonData);
  }

}
